<?php
/**
 * Created by PhpStorm.
 * User: 12133
 * Date: 2024/3/16
 * Time: 16:08
 */

namespace app\controller\index;
use app\model\index\Order AS model;
use app\model\index\OrderInfo AS info;
use app\model\index\Setmenu;
use app\model\index\User AS user;
use app\model\UserAmount AS amount;
use app\model\index\Keyword AS keyword;
use Mpdf\Mpdf;
use think\facade\Db;

class Order extends Base
{
    public function list(){
        $where = [];
        $get = input('get.');
        $post = input('post.');
        if(!empty($get)) $post = $get;
        $order_no = input('order_no','');
        !empty($order_no) && $where[] = ['order_no','like',$order_no];
        !empty($post['status']) && $where[] = ['status','=',$post['status']];
        !empty($post['order']) && $where[] = ['order_no','like','%'.$post['order'].'%'];
        !empty($post['keyword']) && $where[] = ['keyword','like','%'.$post['keyword'].'%'];
        !empty($post['address']) && $parent[] = ['address','like','%'.$post['address'].'%'];
        !empty($post['word_day']) && $parent[] = ['word_day','like','%'.$post['word_day'].'%'];
        !empty($post['word_hover']) && $parent[] = ['word_hover','like','%'.$post['word_hover'].'%'];
        !empty($post['word_type']) && $parent[] = ['word_type','like','%'.$post['word_type'].'%'];
        !empty($post['keyword_type']) && $where[] = ['type','=',$post['keyword_type']];
        !empty($post['price_type']) && $where[] = ['price_type','=',$post['price_type']];
        $rule = json_decode($this->user->rule,true);
        empty($rule) && $rule = [];
        if (!in_array('order',$rule))
            $where[] = ['user_id','=',$this->user->id];
        $order = model::where($where)
            ->with(['user_info','info'])
            ->order('create_time DESC')
            ->paginate(['page' => $this->page,'list_rows' => $this->size]);
        return $this->view('/index/order/list',
            [
                'list' => $order,
                'order' => input('order',''),
                'order_no' => $order_no ?? ''
            ]);
    }

    public function find($order_no){
        $info = model::where('order_no',$order_no)->find();
        $time = $info->word_day == '全年' ? ['day' => 365,'month' => 12] :['day' => 183,'month' => 6];
        $date = [
            'create_date' => date('Y年m月d日'),
            'end_date' => date('Y年m月d日',time() + $time['day'] * 86400)
        ];
//        dd($info->info);
        return $this->view('/index/order/info',[
            'info' => $info,
            'order_no' => $order_no,
            'amount' => floor($info->amount / $this->user->discount),
            'date' => $date,
            'time' => $time
        ]);
    }

    public function info($order_no){
        $info = model::where('order_no',$order_no)->with(['info'])->find();
        return $this->msg($info);
    }

    public function delete($order_no){
        $order = model::where('order_no',$order_no)->find();
        if (!empty($order)){
            $order->delete();
            info::where('order_no',$order_no)->delete();
        }
        return $this->msg();
    }

    public function save()
    {
        $post = input('post.');
        $order = model::where('order_no', $post['order_no'])->find();
        $order->save([
            'image' => $post['image'] ?? null,
            'nickname' => $post['nickname'] ?? null
        ]);
        return $this->msg([
            'order' => $order
        ]);
    }

    public function pay(){
        $web = input('web');
        $nickname = input('nickname');
        $mobile = input('mobile');
        $order_no = input('order_no');
        $order = model::where('order_no',$order_no)->find();
        $amount = $order->amount;
        $buy_year = $order->word_day == '全年' ? 1 : 0.5;
        if (empty($order->id))
            return $this->fail('订单不存在');
        if($this->user->pid == 0) {
            if ($this->user->amount < $amount)
                return $this->fail('余额不足');
        }else{
            $parent = user::where('id',$this->user->pid)->find();
            if ($parent->amount < $amount)
                return $this->fail('余额不足');
        }
        $keywords = info::where('order_no',$order_no)
            ->select()
            ->toArray();
        $area = $keywords[0]['keyword_area'];
        $keywords = array_column($keywords,'keyword');
        $count = info::where('keyword','IN',$keywords)
            ->where('status',2)
            ->where('keyword_area',$area)
            ->where('end_date','>',date('Y-m-d'))
            ->count();
        if ($count > 0) {
            $order->delete();
            return $this->fail('关键词已经被他人下单,无法再购买。即将删除该订单',409);
        }
//        if($pay_type == 1) {
            if ($order->status == 2)
                return $this->fail('订单已经支付过了，无需再次支付');
            if ($order->status != 1)
                return $this->fail('订单无法支付');
//        }
        if(empty($parent)) {
            $this->user->amount = $this->user->amount - $amount;
        }else{
            $parent->amount = $parent->amount - $amount;
        }
        $this->user->save();
        amount::create([
            'order_no' => $order->order_no,
            'user_id' => $this->user->id,
            'pid' => $this->user->pid,
            'amount' => $amount * -1,
            'before_amount' => $this->user->amount + $amount,
            'after_amount' => $this->user->amount,
            'type' => 1
        ]);
//        $end_time = !empty($order->end_date) ? strtotime($order->end_date) : time();
        $order->data([
            'status' => 2,
            'website' => $web,
            'amount' => $amount,
            'buy_year' => $buy_year,
            'nickname' => $nickname,
            'mobile' => $mobile,
            'end_date' => date('Y-m-d',time() + ($buy_year * 365 * 86400))
        ]);
        info::where('order_no',$order->order_no)
            ->save([
                'status' => 2,
                'end_date' => date('Y-m-d',time() + ($buy_year * 365 * 86400))
            ]);
        $order->save();
        return $this->msg();
    }

    public function setmenu_create(){
        $post = input('post.');
        $sid = $post['message']['id'];
        $info = Setmenu::where('id',$sid)->find();
        $pid = empty($this->user->pid) ? $this->user->id : $this->user->pid;
        if (empty($post['keyword_area']))
            return $this->fail('平台未选择,请选择百度或者抖音或全选');
        if (count($post['keyword_area']) == 0)
            return $this->fail('平台未选择,请选择百度或者抖音或全选');
        if (count($post['keyword_area']) == 1)
            $keyword_area = $post['keyword_area'][0];
        else
            $keyword_area = 'all';
        foreach ($post['fuci'] AS $key => $value) {
            $price = keyword::where('keyword', $value)->value('price');
            if (empty($price))
                return $this->fail('请先检测副词:' . $value . '在提交订单');
            if ($price > 6000)
                return $this->fail( $value . '不合格,请更换');
            if ($keyword_area == 'all' || $keyword_area == 'douying') {
                if ($price > 4000)
                    return $this->fail($value . '不符合抖音副词标准,请更换关键词或者更改平台');
            }
        }
        foreach ($post['zhuci'] AS $key => $value){
            $price = keyword::where('keyword',$value)->value('price');
            if (empty($price))
                return $this->fail('请先检测主词:'.$value.'在提交订单');
            if ($price > 20000)
                return $this->fail($value . '为热门词,请更换主词或者单独下单');
            if ($keyword_area == 'all' || $keyword_area == 'douying') {
                if ($price > 13333)
                    return $this->fail($value . '为抖音热门词,请更换关键词或者更改平台或者额单独下单');
            }
        }
        $amount = $keyword_area == 'all' ? floor($info->price * 2) : $info->price;
        $order_no = date('YmdHis').rand(100,999);
        $order = model::create([
            'order_no' => $order_no,
            'type' => 4,
            'user_id' => $pid,
            'price_type' => 1,
            'address' => '全国',
            'amount' => $amount,
            'order_type' => 1,
            'buy_year' => 1,
            'word_day' => '全年',
            'word_type' => '图文,视频',
            'word_hover' => '8:00-20:00',
            'keyword_area' => $keyword_area
        ]);
        $install = [];
        foreach ($post['fuci'] AS $key => $value){
            $install[] = [
                'order_no' => $order_no,
                'keyword' => $value,
                'type' => 5,
                'price' => 0,
                'price_type' => 1,
                'user_id' => $pid,
                'status' => 1,
                'keyword_area' => $keyword_area
            ];
        }
        foreach ($post['zhuci'] AS $key => $value){
            $install[] = [
                'order_no' => $order_no,
                'keyword' => $value,
                'type' => 4,
                'price' => 0,
                'price_type' => 1,
                'user_id' => $pid,
                'status' => 1,
                'keyword_area' => $keyword_area
            ];
        }
        $order->info()->saveAll($install);
        return $this->msg([
            'order_no' => $order_no
        ]);
    }

    public function save_amount(){
        $q = input('q');
        $order_no = input('order_no');
        if ($q == 1) {
            $rule = json_decode($this->user->rule, true);
            empty($rule) && $rule = [];
            if (!in_array('order', $rule))
                return $this->fail('没有权限');
            return $this->msg();
        }else if ($q == 2){
            $amount = input('amount');
            $order = model::where('order_no', $order_no)->find();
            if ($order['type'] != 4) {
                $discount = \app\model\index\User::where('id',$order->user_id)->value('discount');
                if ($discount != 1)
                    $amount = floor($amount * $discount);
            }
            $order->amount = $amount;
            $order->save();
            return $this->msg();
        }else{
            return $this->msg();
        }
    }

    public function save_hetong_corporate_name(){
        $order_no = input('order_no');
        $corporate_name = input('hetong_corporate_name');
        $order = model::where('order_no', $order_no)->find();
        $order->corporate_name = $corporate_name;
        $order->save();
        return $this->msg();
    }

    public function total(){
        $nop = model::where('status',1)->count();
        return $this->msg([
            'nop' => $nop
        ]);
    }

    public function pdf(){
        $html = input('html');
        $order = input('order');
        $html = str_replace(['|-','-|'],['<','>'],$html);
        $html = '<html lang="zh-CN"><head><meta charset="UTF-8"><title>'.$order.'</title><style> .hetong-message{display: none;width: 100%;background-color: #fff;}.hetong-message .button{width: 100%;text-align: center;}.hetong-message .button a{display: inline-block;width: 100px;height: 30px;line-height: 30px;background-color: #1ca3fd;color: #fff;font-size: 16px;margin: 10px;}.hetong-message p{width: 90%;margin:10px 5%;}.hetong-message p span:nth-child(2){float: right;}</style></head><body>'.$html.'</body></html>';
//        $html = htmlspecialchars($html);
//        $encoding_from = 'UTF-8'; // 源编码，根据实际情况替换
//        $encoding_to = 'GBK'; // 目标编码
//        $html = iconv($encoding_from, $encoding_to, $html);
//        dd($html);
        $mpdf = new Mpdf();
        $mpdf->autoScriptToLang = true;
//        $html .= '<head><meta charset="UTF-8"></head>';
        $mpdf->WriteHTML($html);
// 设置PDF文档的输出方式：I表示在浏览器中内嵌显示，D表示作为附件下载，F表示保存到服务器文件
        $mpdf->Output($order.'.pdf', 'D');
    }
}